package com.example.s.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.s.Activity.SelectLabelActivity;
import com.example.s.R;
import com.example.s.adapter.InnerHolder;
import com.example.s.adapter.MyRecyclerViewAdapter;
import com.example.s.application.MyApplication;
import com.example.s.bean.User;
import com.example.s.network.OnMyNetworkListener;
import com.example.s.utils.LiveDataBus;
import com.example.s.utils.MyUtils;
import com.example.s.utils.TCUpload;
import com.google.gson.Gson;
import com.tencent.cos.xml.exception.CosXmlClientException;
import com.tencent.cos.xml.exception.CosXmlServiceException;
import com.tencent.cos.xml.model.CosXmlRequest;
import com.tencent.cos.xml.transfer.COSXMLUploadTask;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpLoadFragment extends BaseFragment {
    private TextView author;
    private TextView release;
    private EditText content;
    private TextView maxSize;
    private RecyclerView photoRv;
    private FrameLayout addVideo;
    private LinearLayout selectLabel;
    private LinearLayout originalTag;
    private ImageView cover;
    private TextView selectCover;
    private List<Uri> photoList = new ArrayList<>();
    private MyRecyclerViewAdapter<Uri> mPhotoAdapter;
    private LinearLayout photoContainer;
    private FrameLayout addPhoto;
    private LinearLayout contentContainer;
    private VideoView vv;
    private ImageView videoCover;
    private Uri videoUri;
    private EditText titleContent;
    private TextView tagTitle;
    private Uri coverUri;

    private Uri selectedVideo;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_upload;
    }

    @Override
    public void initView(View view) {
        tagTitle = (TextView) findViewById(R.id.tagTitle);
        titleContent = (EditText) findViewById(R.id.title_content);
        author = (TextView) findViewById(R.id.author);
        release = (TextView) findViewById(R.id.release);
        content = (EditText) findViewById(R.id.content);
        maxSize = (TextView) findViewById(R.id.maxSize);
        photoRv = (RecyclerView) findViewById(R.id.photoRv);
        addVideo = (FrameLayout) findViewById(R.id.addVideo);
        selectLabel = (LinearLayout) findViewById(R.id.selectLabel);
        originalTag = (LinearLayout) findViewById(R.id.originalTag);
        cover = (ImageView) findViewById(R.id.cover);
        selectCover = (TextView) findViewById(R.id.selectCover);

        contentContainer = (LinearLayout) findViewById(R.id.contentContainer);
        vv = (VideoView) findViewById(R.id.vv);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        User user = MyApplication.getInstance(A).getUser();
        if (user != null)
            author.setText(user.getNickName());
        LiveDataBus liveDataBus = LiveDataBus.getInstance();
        content.setFilters(new InputFilter[]{new InputFilter.LengthFilter(300)});
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                maxSize.setText(s.length() + "/300");
            }
        });

        setPhotoAdapter();
        liveDataBus.with("photoRealWidth", Integer.class).observe(getActivity(), new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                if (integer != null) {
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) addVideo.getLayoutParams();
                    layoutParams.width = integer;
                    layoutParams.height = integer;
                    addVideo.setLayoutParams(layoutParams);
                    vv.setLayoutParams(layoutParams);
                }
            }
        });

        addVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                startActivityForResult(intent, 3);
            }
        });

        selectLabel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(getActivity(), SelectLabelActivity.class), 100);
            }
        });
        selectCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 4);
            }
        });
    }

    private void setPhotoAdapter() {
        photoList.add(null);
        contentContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                int width = contentContainer.getWidth();
                int px = MyUtils.getInstance().dip2px(getContext(), 20);
                int realWidth = (width - px) / 3;
                LiveDataBus.getInstance().with("photoRealWidth", Integer.class).setValue(realWidth);
                Log.d(TAG, "onGlobalLayout: " + realWidth);
                contentContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });

        photoRv.setLayoutManager(new GridLayoutManager(getContext(), 3));
        photoRv.setAdapter(mPhotoAdapter = new MyRecyclerViewAdapter<Uri>(photoList, R.layout.rv_upload_photo_item) {
            @Override
            public void handleData(InnerHolder holder, Uri item) {
                ImageView cover = holder.getView(R.id.cover);
                LiveDataBus.getInstance().with("photoRealWidth", Integer.class).observe(getActivity(), new Observer<Integer>() {
                    @Override
                    public void onChanged(Integer integer) {
                        if (integer != null) {
                            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) cover.getLayoutParams();
                            layoutParams.width = integer;
                            layoutParams.height = integer;
                            cover.setLayoutParams(layoutParams);
                        }
                    }
                });

                ImageView add = holder.getView(R.id.add_bg);
                ImageView delete = holder.getView(R.id.delete);
                add.setVisibility(View.GONE);
                delete.setVisibility(View.VISIBLE);
                if (item != null) {
                    cover.setImageURI(item);
                }
                cover.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (holder.getAdapterPosition() >= photoList.size() - 1) {
                            Intent intent = new Intent(Intent.ACTION_PICK, null);
                            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                            startActivityForResult(intent, 2);
                        }
                    }
                });
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        photoList.remove(item);
                        mPhotoAdapter.notifyDataSetChanged();
                    }
                });

                if (holder.getAdapterPosition() >= photoList.size() - 1) {
                    cover.setImageResource(R.mipmap.upload_add_bg);
                    cover.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    add.setVisibility(View.VISIBLE);
                    add.setBackgroundResource(R.mipmap.upload_add);
                    delete.setVisibility(View.INVISIBLE);

                }
                Log.d(TAG, "handleData: " + holder.getAdapterPosition());
                Log.d(TAG, "handleData: " + holder.getLayoutPosition());
            }

        });


        release.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String titleStr = titleContent.getText().toString();
                String contentStr = content.getText().toString();
                String tagStr = tagTitle.getText().toString();
                if (MyUtils.getInstance().isHasEmpty(
                        titleStr,
                        contentStr

                ) || photoList.size() == 0 || "".equals(tagStr) || "选择标签".equals(tagStr)) {
                    Toast.makeText(A, "请输入完整内容!", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                stringObjectHashMap.put("uid", "161199");
                stringObjectHashMap.put("title", titleStr);
                stringObjectHashMap.put("content", contentStr);
                stringObjectHashMap.put("tag", tagStr);
                TCUpload tcUpload = new TCUpload(A);
                List<Uri> nList = new ArrayList<>();
                HashMap<String, Uri> nMap = new HashMap<>();
                for (Uri uri : photoList) {
                    if (uri != null) {
                        nList.add(uri);
                        nMap.put("img", uri);
                    }
                }
                if (selectedVideo != null) {
                    nList.add(selectedVideo);

                    nMap.put("video", selectedVideo);
                }
                nList.add(coverUri != null ? coverUri : photoList.get(0));
                nMap.put("cover", coverUri != null ? coverUri : photoList.get(0));
                final boolean[] is = {true};
                int i = 0;
                StringBuilder mgUrl = new StringBuilder();
                mgUrl.append("[");
                final String[] videoUrl = {""};
                final String[] coverUrl = {""};

                try {
                    for (Map.Entry<String, Uri> stringUriEntry : nMap.entrySet()) {
                        Log.d(TAG, "onClick: " + stringUriEntry.getKey());
                        if (!is[0]) {
                            break;
                        }
                        int finalI = i;
                        tcUpload.uploadUri("item", stringUriEntry.getValue(), new TCUpload.OnUploadListener() {
                            @Override
                            public void onSuccess(COSXMLUploadTask.COSXMLUploadTaskResult result) {
                                Log.d(TAG, "onSuccess: " + result.accessUrl);
                                if (stringUriEntry.getKey().equals("img")) {
                                    mgUrl.append("src:");
                                    mgUrl.append(result.accessUrl);
                                    mgUrl.append(",");
                                } else if (stringUriEntry.getKey().equals("video")) {
                                    videoUrl[0] = result.accessUrl;
                                } else {
                                    coverUrl[0] = result.accessUrl;

                                }
                                if (finalI == nList.size() - 1) {
                                    mgUrl.delete(mgUrl.length() - 1, mgUrl.length()).append("]");
                                    stringObjectHashMap.put("img", mgUrl.toString());
                                    stringObjectHashMap.put("video", videoUrl[0]);
                                    stringObjectHashMap.put("cover", coverUrl[0]);
                                    N.post("/api/upload_app", stringObjectHashMap, true, new OnMyNetworkListener() {
                                        @Override
                                        public void success(JSONObject response) {
                                            Toast.makeText(A, "上传成功", Toast.LENGTH_SHORT).show();
                                        }

                                        @Override
                                        public void fail(JSONObject response) {
                                            Toast.makeText(A, "上传失败,检查网络！", Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }

                            @Override
                            public void onFail(CosXmlRequest request, CosXmlClientException clientException, CosXmlServiceException serviceException) {
                                if (clientException != null) {
                                    Toast.makeText(A, "上传失败,检查网络！", Toast.LENGTH_SHORT).show();
                                }else {
                                    Toast.makeText(A, "服务端异常！", Toast.LENGTH_SHORT).show();
                                }
                                    is[0] = false;
                            }
                        });
                        i++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(A, "不能上传文件！", Toast.LENGTH_SHORT).show();
                }


            }
        });
    }


    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
        if(selectedVideo!=null){
            A.getSharedPreferences("item").edit().putString("videoUri",selectedVideo.toString()).commit();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");
        String string = A.getSharedPreferences("item").getString("videoUri", "");
        if(!"".equals(string)){
            selectedVideo = Uri.parse(string);
            vv.setVideoURI(selectedVideo);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 100 && resultCode == 100 && data != null) {
            String tag = data.getStringExtra("tag");
            tagTitle.setText(tag);
        }
        if (requestCode == 2 && resultCode == getActivity().RESULT_OK && data != null) {
            Uri uri = data.getData();
            photoList.add(0, uri);
            mPhotoAdapter.notifyDataSetChanged();
            if (cover.getDrawable() == null) {
                cover.setImageURI(uri);
            }
        }
        if (requestCode == 3 && resultCode == getActivity().RESULT_OK && data != null) {
            selectedVideo = data.getData();
//            String[] filePathColumn = {MediaStore.Video.Media.DATA};
//
            Log.d(TAG, "onActivityResult: " + selectedVideo);
            vv.setVisibility(View.VISIBLE);
            videoUri = selectedVideo;
            vv.setVideoURI(selectedVideo);
//            vv.start();
        }
        if (requestCode == 4 && resultCode == getActivity().RESULT_OK && data != null) {
            coverUri = data.getData();
            cover.setImageURI(data.getData());
        }
    }
}
